﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[ExecuteInEditMode]
public class MatterGridBehaviour : MonoBehaviour
{
//    public TextMesh testTextmesh;
    public GameObject Solid;
    public Material solidM;

    public GameObject Liquid;
    public Material LiquidM;

    public GameObject Gas;
    public UVTileSpeed[] Gasuv;     //0为左下角 1 为 左上角 2 为右下角 3 为右上角
    
    public Collider2D collider;

    public UnityEngine.SpriteRenderer editorShow;

    // Use this for initialization
    void Awake()
    {
#if UNITY_EDITOR
        if (!UnityEditor.EditorApplication.isPlaying)
        {
            editorShow.enabled = true;
            solidM = Solid.GetComponent<MeshRenderer>().sharedMaterial;

            LiquidM = Liquid.GetComponent<MeshRenderer>().sharedMaterial;
//            gasM = Gas.GetComponent<MeshRenderer>().sharedMaterial;
        }
        else
        {
            solidM = Solid.GetComponent<MeshRenderer>().material;
            LiquidM = Liquid.GetComponent<MeshRenderer>().material;
        }
#else
            editorShow.enabled = false;
            solidM = Solid.GetComponent<MeshRenderer>().material;
#endif
    }

    void Start ()
    {
    }
    float currentshowTemperature = float.NaN;	
	// Update is called once per frame
	void Update ()
    {
    } 

    public MatterGrid mg;
    public void SetMatterGrid(MatterGrid thegrid)
    {
        mg = thegrid;
        thegrid.UpdateEvent += DelayUpdate;
        DelayUpdate();
    }

    public override string ToString()
    {
        return string.Format("当前温度 : {0} , 当前质量 : {1},总能量 {2}", mg.Temperature, mg.TotalMass, mg.GetTotalEnergy());
    }


    float[] SolidShow = new float[3];
    string[] SolidTextureName = new string[3];
    Texture2D[] SolidTexture = new Texture2D[3];

    Texture2D[] LiquidTexture = new Texture2D[3];
    string[] LiquidTextureName = new string[3];
    //为了控制性能 不做即使更新 每 500 ms 左右 刷新 一次数据
    public void DelayUpdate()
    {
        UpdateSolidShow();
        UpdateGasShow();
        UpdateLiquidShow();
    }


    void UpdateSolidShow()
    {
        //计算固体的体积
        float a = mg.GetSolidVolume();
        Solid.transform.localScale = new Vector3(1.0f, Mathf.Min(1.0f, a), 1.0f);
        //计算固体的材质 
        //取质量前3 的物质 进行显示
        int count = Mathf.Min(mg.SolidMatterByMassShowPriority.Count, 3);
        if (count == 0)
        {
            Solid.SetActive(false);
            collider.enabled = false;
        }
        else
        {
            Solid.SetActive(true);
            collider.enabled = true;
            float totalvalue = 0.0f;
            for (int i = 0; i < count; i++)
            {
                SolidShow[i] = mg.SolidMatterByMassShowPriority[i].Mass * mg.SolidMatterByMassShowPriority[i].matterType.ShowPriority;
                totalvalue += SolidShow[i];
                string ss = mg.SolidMatterByMassShowPriority[i].matterType.SolidSpriter;
                if (ss != SolidTextureName[i])
                {
                    SolidTexture[i] = AssetLoader.Load<Texture2D>(ss, ".png");
                    SolidTextureName[i] = ss;
                }
            }
            for (int i = count; i < 3; i++)
            {
                SolidShow[i] = 0.0f;
            }
            solidM.SetTexture("_MainTex0", SolidTexture[0]);
            solidM.SetTexture("_MainTex1", SolidTexture[1]);
            solidM.SetTexture("_MainTex2", SolidTexture[2]);
            solidM.SetFloat("_MainTex0Proportion", 1.0f);
            solidM.SetFloat("_MainTex1Proportion", 0.0f);
            solidM.SetFloat("_MainTex2Proportion", 0.0f);
        }
    }

    void UpdateGasShow()
    {
        if (mg.GetGasPressure() == 0.0f)
        {
            Gas.SetActive(false);
        }
        else
        {
            Gas.SetActive(true);
            //首先 检查一下 有没有气体
            //根据 gasMovement 来计算 材质的运动
            // Gasuv;     //0为左下角 1 为 左上角 2 为右下角 3 为右上角
            //gasMovement = new float[4];                      //0为上 1为右 2 为下  3为左   大于0 为往外运动
            Vector2 p0 = new Vector2();
            Vector2 p1 = new Vector2();
            Vector2 p2 = new Vector2();
            Vector2 p3 = new Vector2();

            //        if(mg.X ==1 && mg.Y == 13)
            //        {
            //            Debug.Log(string.Format("x {0} y {1} ,{2} , {3} , {4} ,{5}",mg.X,mg.Y, mg.gasMovement[0], mg.gasMovement[1], mg.gasMovement[2], mg.gasMovement[3]));
            //        }

            p1.y = -(mg.gasMovement[0] + mg.gasMovement2[0]) / 2.0f;
            p3.y = -(mg.gasMovement[0] + mg.gasMovement2[0]) / 2.0f;
            p2.x = -(mg.gasMovement[1] + mg.gasMovement2[1]) / 2.0f;
            p3.x = -(mg.gasMovement[1] + mg.gasMovement2[1]) / 2.0f;
            p0.y = (mg.gasMovement[2] + mg.gasMovement2[2]) / 2.0f;
            p2.y = (mg.gasMovement[2] + mg.gasMovement2[2]) / 2.0f;
            p1.x = (mg.gasMovement[3] + mg.gasMovement2[3]) / 2.0f;
            p0.x = (mg.gasMovement[3] + mg.gasMovement2[3]) / 2.0f;
            Gasuv[0].SetSpeed(p0);
            Gasuv[1].SetSpeed(p1);
            Gasuv[2].SetSpeed(p2);
            Gasuv[3].SetSpeed(p3);
        }
    }

    void UpdateLiquidShow()
    {
        //计算固体的体积
        float a = mg.GetLiquidVolume();
        Liquid.transform.localScale = new Vector3(1.0f, Mathf.Min(1.0f, a), 1.0f);
        //计算固体的材质 
        //取质量前3 的物质 进行显示
        //TODO 按照密度顺序 显示 目前显示第一个
        if (mg.liquidMatterByBoil.Count == 0)
        {
            Liquid.SetActive(false);
        }
        else
        {
            Liquid.SetActive(true);
            string ss = mg.liquidMatterByBoil[0].matterType.LiquidSpriter;
            if (ss != LiquidTextureName[0])
            {
                LiquidTexture[0] = AssetLoader.Load<Texture2D>(ss, ".png");
                LiquidTextureName[0] = ss;
            }

            LiquidM.SetTexture("_MainTex0", LiquidTexture[0]);
            LiquidM.SetTexture("_MainTex1", LiquidTexture[1]);
            LiquidM.SetTexture("_MainTex2", LiquidTexture[2]);
            LiquidM.SetFloat("_MainTex0Proportion", 1.0f);
            LiquidM.SetFloat("_MainTex1Proportion", 0.0f);
            LiquidM.SetFloat("_MainTex2Proportion", 0.0f);
        }
    }

#if UNITY_EDITOR
    [UnityEditor.MenuItem("Tools/One")]
    public static void BuildAsset()
    {
        for(int i = 0 ; i < 2;i++)
        {
            for(int j = 0 ; j < 2;j++)
            {
                Mesh a = new Mesh();
                Vector2[] uvs = new Vector2[4];
                uvs[0] = new Vector2(0.0f, 0.0f);
                uvs[1] = new Vector2(1.0f, 0.0f);
                uvs[2] = new Vector2(1.0f, 1.0f);
                uvs[3] = new Vector2(0.0f, 1.0f);

                Vector3[] positions = new Vector3[4];
                positions[0] = new Vector3(0.0f + i * 0.5f, 0.0f + j * 0.5f, 0.0f);
                positions[1] = new Vector3(0.5f + i * 0.5f, 0.0f + j * 0.5f, 0.0f);
                positions[2] = new Vector3(0.5f + i * 0.5f, 0.5f + j * 0.5f, 0.0f);
                positions[3] = new Vector3(0.0f + i * 0.5f, 0.5f + j * 0.5f, 0.0f);
                a.vertices = positions;
                a.uv = uvs;
                int[] t = { 2, 1, 0, 3, 2, 0 };
                a.triangles = t;
                UnityEditor.AssetDatabase.CreateAsset(a, string.Format("Assets/gasgrid{0}{1}.asset",i,j));
            }
        }
    }

    [UnityEditor.MenuItem("Tools/Two")]
    public static void BuildAsset2()
    {
        Texture2D t = new Texture2D(256, 256, TextureFormat.RGBA32,false);
        for(int i = 0 ; i < 64;i++)
        {
            for(int j = 0; j < 64;j++)
            {
                Color c;
                if(Random.Range(0.0f,1.0f) < 0.02f)
                {
                    c = Color.white;
                    c.a = 1.0f;
                }
                else
                {
                    c = Color.white;
                    c.a = 0.0f;
                }
                for (int m = 0; m < 4;m++ )
                {
                    for(int n = 0 ; n < 4 ; n++)
                    {
                        t.SetPixel(4 * i + m, 4 * j + n, c);
                    }
                }

            }
        }
        byte[] bytes = t.EncodeToPNG();
        System.IO.Stream str = System.IO.File.Open("Assets/a.png", System.IO.FileMode.Create);
        str.Write(bytes, 0, bytes.Length);
        str.Close();
    }

    [UnityEditor.MenuItem("Tools/thrid")]
    public static void BuildAsset3()
    {
        Texture2D t = new Texture2D(16, 16, TextureFormat.RGBA32, false);
        for (int i = 0; i < 16; i++)
        {
            for (int j = 0; j < 16; j++)
            {
                for (int m = 0; m < 4; m++)
                {
                    for (int n = 0; n < 4; n++)
                    {
                        t.SetPixel(i,j,Color.white);
                    }
                }
            }
        }
        byte[] bytes = t.EncodeToPNG();
        System.IO.Stream str = System.IO.File.Open("Assets/d.png", System.IO.FileMode.Create);
        str.Write(bytes, 0, bytes.Length);
        str.Close();
    }
#endif
}
